set matsize 8000
set more off
clear all

cap log close
log using an_tfp_ind,t replace

*** Program to run verious estimators of TFP by industry

use sample, clear

xtset id year 
tab year,gen(y_)
global yrdum y_2-y_10
tab ind,gen(i_)
global inddum i_2-i_18

egen x = max(year),by(id)
gen exit = x==year
tab exit
drop x

foreach num of numlist 15 17 18 19 20 21 22 24 25 26 27 28 29 31 33 34 35 36 {
*foreach num of numlist 35 36 {
*foreach num of numlist 15 17 {
display _newline "Industry number " `num' _newline
/*
  qui reg logs loga logm loge $yrdum if ind==`num', vce(cluster id)
  predict tfp_`num', resid
  lincom 1-loga-loge-logm
  est store olsest

  qui opreg logs if ind==`num', exit(exit) state(loga) proxy(logi) free(logm loge) cvars($yrdum) vce(bootstrap, reps(20))
  predict tfp_op_`num'
  lincom 1-loga-loge-logm
  est store opest

  qui levpet logs if ind==`num', free(loge $yrdum) proxy(logm) capital(loga) revenue reps(20) 
  predict tfp_lp_`num', omega
  lincom 1-loga-loge-logm
  est store lpest

  esttab *est, keep(loga loge logm)              ///
         b(%10.4f) se(%10.4f) star stats(r2 rmse F df_m N N_clust) nogaps  
*/
  acfest logs if ind==`num', state(loga) proxy(logm) free(loge) nbs(40) ///
         robust nodum
  codebook id if e(sample)		 
  lincom 1-loga-loge-logm
  predict tfp_acf_`num', omega	 
}

acfest logs, state(loga) proxy(logi) free(loge) nbs(40) ///
       robust invest intmat(logm) nodum
lincom 1-loga-loge-logm
cap drop tfp_acf
predict tfp_acf, omega
hist tfp_acf

acfest logs, state(loga) proxy(logm) free(loge) nbs(40) ///
       robust  nodum
lincom 1-loga-loge-logm
cap drop tfp_acfm
predict tfp_acfm, omega
hist tfp_acfm
		 
*foreach var in tfp tfp_op tfp_lp tfp_acf {
foreach var in tfp_acf {
  qui gen `var'_i = .
  foreach num of numlist 15 17 18 19 20 21 22 24 25 26 27 28 29 31 33 34 35 36 {
    qui replace `var'_i = `var'_`num' if ind==`num'
    drop `var'_`num'
  }
}

drop y_* i_*
keep id year tfp*
do cleanfile
sum
save tfp_ind, replace

log close
